import { Component, OnInit } from '@angular/core';
import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { CAKE_ORDER_SERVICE_STATUS_OPTION } from '../../../constant/dictionary';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-serve-back',
  templateUrl: './serve-back.component.html',
})
export class ServeBackComponent implements OnInit {
  entity: any = {};
  validateForm: FormGroup;
  cakeOrderServiceStatusOption: any []= CAKE_ORDER_SERVICE_STATUS_OPTION;
  isLoading: boolean = false;
  businessService: any;

  allProducts:any [] = [];
  constructor(private fb: FormBuilder,
              private modal: NzModalRef,
              public message: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      serviceStatus: [this.entity.serviceStatus, [Validators.required]],
      goodsQuantity: [this.entity.goodsQuantity, [Validators.required]],
      goodsUnitPrice: [this.entity.goodsUnitPrice, [Validators.required]],
      productId: [this.entity.productId, []],
      goodsTotalPrice: [this.entity.goodsTotalPrice, [Validators.required]],
      remark: [this.entity.remark, [Validators.required, Validators.maxLength(200)]],
    });
  }

  countTotalPrice(e,contrl){
    console.log( this.validateForm.value)
    let goodsTotalPrice = parseFloat((this.validateForm.value.goodsQuantity * this.validateForm.value.goodsUnitPrice).toFixed(2));
    this.validateForm.controls.goodsTotalPrice.setValue(goodsTotalPrice);
  }

  submitForm(): void {
    if(this.entity.serviceStatus == 2){
      return;
    }
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      this.isLoading = true;
      this.businessService.auditing(this.entity.id, this.validateForm.value).then((res) => {
        if (res.status.toString().startsWith('20')) {
          this.modal.close(true);
        } else {
          this.message.warning(res.message);
        }
        this.isLoading = false;
      }, error => {
        this.message.error(error.message ? error.message : error.error);
        this.isLoading = false;
      });
    }
  }

  close() {
    this.modal.destroy();
  }
}
